import axios from 'axios';
import type { AxiosRequestConfig, AxiosResponse } from 'axios';
import { Message, Modal } from '@arco-design/web-vue';
import { useUserStore, useAppStore } from '@/store';
import { getToken } from '@/utils/auth';

export interface HttpResponse<T = unknown> {
  status: number;
  msg: string;
  code: string;
  res: string;
  data: T;
}
axios.interceptors.request.use(
  async (config: AxiosRequestConfig) => {
    // let each request carry token
    // this example using the JWT token
    // Authorization is a custom headers key
    // please modify it according to the actual situation
    const token = getToken();
    if (token) {
      if (!config.headers) {
        config.headers = {};
      }
      config.headers.Authorization = token;
    }
    const appStore = useAppStore();
    config.baseURL = await appStore.getBaseUrl();
    return config;
  },
  (error) => {
    // do something
    return Promise.reject(error);
  }
);
// add response interceptors
axios.interceptors.response.use(
  (response: AxiosResponse<HttpResponse>) => {
    const res = response.data;
    switch (res.res) {
      case 'FAILURE':
      case 'EXCEPTION':
      case 'QUESTION':
        Message.error({
          content: res.msg || '请求错误',
          duration: 5 * 1000,
        });
        if (res.code === 'EXCEPTION4LOGIN') {
          Modal.error({
            title: '确认退出',
            content: '你已经退出, 你可以取消并停留到当前页面，或者重新登录！',
            okText: '重新登录',
            async onOk() {
              const userStore = useUserStore();
              await userStore.logout();
              window.location.reload();
            },
          });
        }
        return Promise.reject(res);
      case 'SUCCESS':
      default:
        return Promise.resolve(res);
    }
  },
  (error) => {
    Message.error({
      content: error.msg || '请求异常',
      duration: 5 * 1000,
    });
    return Promise.reject(error);
  }
);
